/******************************************************************************
*
*   Filename    : dbutton.c
*   Author      : Ariff Ehsan
*   Date        : Oct. 29, 2009
*   Description : Driver for joystick/button.
*                 Modified from CircleOS button driver.
*
******************************************************************************/

#include "FreeRTOS.h"
#include "task.h"

#include "dbutton.h"

void BUTTON_Init( void );
static void BUTTON_vTask( void *pvParameters );
void BUTTON_Update( void );

xTaskHandle button_xHandle;

void BUTTON_Configuration( void )
    {
    /* create toolbar task */
    xTaskCreate( BUTTON_vTask, ( signed portCHAR * ) "Button",
                 configMINIMAL_STACK_SIZE, NULL, button_TASK_PRIORITY, button_xHandle );
    }

void BUTTON_Init( void )
    {
    /* Enable BUTTON GPIO clock */
    RCC_APB2PeriphClockCmd( GPIO_BUTTON_PERIPH, ENABLE );

    GPIO_InitTypeDef GPIO_InitStructure;
    
    /* Configure pin as floating input */
    GPIO_InitStructure.GPIO_Pin   = GPIO_BUTTON_PIN;
    GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_IN_FLOATING;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

    GPIO_Init( GPIOx_BUTTON, &GPIO_InitStructure );

    GPIO_InitStructure.GPIO_Pin   = GPIO_JOYSTICK_L_PIN | GPIO_JOYSTICK_R_PIN | GPIO_JOYSTICK_U_PIN | GPIO_JOYSTICK_D_PIN;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
    GPIO_Init( GPIOx_JOYSTICK, &GPIO_InitStructure );
    }

static void BUTTON_vTask( void *pvParameters )
    {
    const portTickType xDelay25 = 25 / portTICK_RATE_MS;
    portTickType xLastWakeTime = xTaskGetTickCount();
    
    BUTTON_Init();
    
    while ( 1 )
        {
        vTaskDelayUntil( &xLastWakeTime, xDelay25 );
        BUTTON_Update();
        }
    }

void BUTTON_Update( void )
    {
    u8 state;
    
    state = GPIO_ReadInputDataBit( GPIOx_BUTTON, GPIO_BUTTON_PIN );
    state = GPIO_ReadInputDataBit(GPIOx_JOYSTICK, GPIO_JOYSTICK_U_PIN);
    state = GPIO_ReadInputDataBit( GPIOx_JOYSTICK, GPIO_JOYSTICK_R_PIN );
    state = GPIO_ReadInputDataBit(GPIOx_JOYSTICK, GPIO_JOYSTICK_L_PIN);
    state = GPIO_ReadInputDataBit(GPIOx_JOYSTICK, GPIO_JOYSTICK_D_PIN);
    }